//
//  LZTabBar.m
//  LZHundredJie
//
//  Created by apple on 16/3/27.
//  Copyright © 2016年 m14a.cn. All rights reserved.
//

#import "LZTabBar.h"
#import "LZPublishViewController.h"

@interface LZTabBar ()

/** 添加按钮*/
@property (nonatomic, weak) UIButton *plusBtn;
/** 上一次点击的tabBar按钮 */
@property (nonatomic, weak) UIControl *previousClickedTabBarButton;

@end

@implementation LZTabBar

// 添加子控件
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 创建一个按钮
        UIButton *plusBtn = [[UIButton alloc] init];
        // 设置背景图片
        [plusBtn setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [plusBtn setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateSelected];
        // 添加监听事件
        [plusBtn addTarget:self action:@selector(publishClick) forControlEvents:UIControlEventTouchUpInside];
        // 根据自己内容(图片,标题)去计算尺寸
        [plusBtn sizeToFit];
        // 添加到系统的LZTabBar对象上
        [self addSubview:plusBtn];
        self.plusBtn = plusBtn;
    }
    return self;
}

- (void)publishClick
{
    [self.window.rootViewController presentViewController:[[LZPublishViewController alloc] init] animated:NO completion:nil];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 设置plusBtn位置和尺寸
    self.plusBtn.center = CGPointMake(self.width * 0.5, self.height * 0.5);
    
    // 计算按钮宽度和高度
    CGFloat btnW = self.width / 5;
    CGFloat btnH = self.height;
    CGFloat btnY = 0;
    // 获得子元素个数
//    NSInteger count = self.subviews.count;
    // 设置索引
    NSInteger index = 0;
    
    for (UIControl *tabBarButton in self.subviews) {
        // 不是UITabBarButton类,返回
        if (![tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")])
            continue;
        
        if (index == 0 && self.previousClickedTabBarButton == nil) { // 最前面的tabBarButton
            self.previousClickedTabBarButton = tabBarButton;
        }
        
        CGFloat btnX = index * btnW;
        // 设置尺寸
        tabBarButton.frame = CGRectMake(btnX, btnY, btnW, btnH);
        index++;
        if (index == 2) {
            index++;
        }
        
        // 添加监听事件
        // 监听点击
        // 短时间内连续点击按钮就会触发UIControlEventTouchDownRepeat事件
        //        [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDownRepeat];
        [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
}

- (void)tabBarButtonClick:(UIControl *)tabBarButton
{
    
//    LZLog(@"--%zd", tabBarButton.tag)
    // 发出通知,告诉外界，tabBarButton被重复点击了
    if (self.previousClickedTabBarButton == tabBarButton) { // 两次点击的是同一个
        [LZNotificationCenter postNotificationName:LZTabBarButtonDidRepeatClickNotification object:nil userInfo:nil];
    }
    // 保存这次点击的给上一次按钮
    self.previousClickedTabBarButton = tabBarButton;
}


@end
